package org.gas.barapraja.proc;

import org.apache.log4j.Logger;
import org.gas.barapraja.handler.BindRequestHandler;
import org.gas.barapraja.handler.MultiMsgHandler;
import org.gas.barapraja.handler.RequestHandler;
import org.gas.barapraja.handler.SingleMsgHandler;
import org.gas.barapraja.proc.buffer.AppQueuePool;

import com.logica.smpp.Data;
import com.logica.smpp.pdu.BindRequest;
import com.logica.smpp.pdu.Request;
import com.logica.smpp.pdu.Response;
import com.logica.smpp.pdu.SubmitMultiSM;
import com.logica.smpp.pdu.SubmitSM;

public class InPduProcessor extends PduProcessor {
	
	private static final Logger logger=Logger.getLogger(InPduProcessor.class);
	
	private boolean bound=false;
	
	public InPduProcessor() {
		AppQueuePool.pduQueueInstance().queue(this);
	}
	
	public InPduProcessor(GasSmscSession session){
		setSession(session);
		session.setPduProcessor(this);
		AppQueuePool.pduQueueInstance().queue(this);
	}

	@Override
	public void clientRequest(Request request) {
		Response response = null;
		RequestHandler handler;
		int commandId=request.getCommandId();
		int status;
		if(!bound){
			BindRequestHandler bindHandler=new BindRequestHandler(this);
			status=bindHandler.handleRequest((BindRequest)request);
			if(status==Data.ESME_ROK){
				bound=true;
				logger.info("user bound: ");
			}else{
				bound=false;
				AppQueuePool.pduQueueInstance().dequeue(this);
				logger.info("failed to bound user");
			}
		}else{
			response=request.getResponse();
			switch(commandId){
			case Data.SUBMIT_SM:
				handler=new SingleMsgHandler(this);
				handler.handleRequest((SubmitSM)request);
				break;
			case Data.SUBMIT_MULTI:
				handler=new MultiMsgHandler(this);
				handler.handleRequest((SubmitMultiSM)request);
				break;
			case Data.UNBIND:
				bound=false;
				AppQueuePool.pduQueueInstance().dequeue(this);
				break;
			}
			serverResponse(response);
			if(commandId==Data.UNBIND){
				logger.info("stopping session");
				session.stop();
				AppQueuePool.pduQueueInstance().dequeue(this);
				bound=false;
			}
		}
	}

	@Override
	public void serverRequest(Request request) {
		logger.debug("server request: "+request.debugString());
		session.sendPdu(request);

	}

	@Override
	public void clientResponse(Response response) {
		logger.debug("client response: "+response.debugString());

	}

	@Override
	public void serverResponse(Response response) {
		logger.debug("server response: "+response.debugString());
		session.sendPdu(response);

	}

}
